import axios from 'axios'
import store from '../store'

const Ajax = axios.create({
    baseURL:'/apis',
    timeout:5000
})

//实现请求拦截
// 再拦截其中，如果没有问题，直接返回AxiosRequestConfig，否则返回Promise.reject方法，这个方法会在Ajax.request的catch回调上捕获
Ajax.interceptors.request.use(function(config) {
    let token = store.getState().common.token,
    otherPath = ['/user/login'] //不需要进行请求拦截的请求地址

    if (otherPath.includes(config.url)) {
        return config
    } else {
        if (!token) {
            return Promise.reject({code: 400, message: 'token参数不存在'})
        } else {
            config.headers.token = token
            return config
        }
    }
})

export default req => {
    if(!req.url) throw new Error('异步请求，url地址必传')

    return new Promise(resolve => {
        Ajax.request({
            url:req.url,
            method: req.method || 'get',
            data: req.data || {},
            params: req.params || {},
            //文件上传进度的回调函数
            // onUploadProgress?: (progressEvent: any) => void; 他需要接收一个回调函数
            onUploadProgress: req.fileUpload || ( () => {} )
        }).then(({data}) => {
            resolve(data)
        }).catch(e => {
            console.log(e);
            resolve({code:500,message:'后端接口问题，请联系后端处理'})
        })
    })
}